package com.dfbz.多线程版在线聊天;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static void main(String[] args) throws IOException {
        //与服务器端请求连接
        ServerSocket socket = new ServerSocket(55555);

       while (true){
           Socket accept = socket.accept();
           System.out.println(socket.getInetAddress().getHostAddress() + "已与您连接成功");
           try {
               Thread.sleep(1000);
               System.out.println("请输入消息,按ENTER发送");
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           // 读取客户端数据
           InputStream is = accept.getInputStream();
           // 缓冲字符输入流(读取客户端数据更加方便)
           BufferedReader br = new BufferedReader(new InputStreamReader(is));
           OutputStream outputStream = accept.getOutputStream();
           BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
           //线程1:读客户端发过来的消息
           new Thread() {
               @Override
               public void run() {
                   try {
                       while (true) {
                           String msg = br.readLine();//读一整行的消息
                           if(msg.equals("88")){
                               System.out.println("聊天结束......");
                               try {
                                   Thread.sleep(1000);
                                   System.out.println(socket.getInetAddress().getHostAddress() + "已与您断开连接: ");
                               } catch (InterruptedException e) {
                                   e.printStackTrace();
                               }
                               System.exit(0);//
                               break;
                           }else {
                               System.out.println("来自客户端的消息:"+msg);
                           }
                       }
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }.start();
           //线程2:向客户端发送信息
           new Thread() {
               @Override
               public void run() {
                   try {
                       while (true) {
                           String msg = new Scanner(System.in).nextLine();
                           //向服务器发送消息
                           bw.write(msg);
                           //写完换行
                           bw.newLine();
                           bw.flush();
                       }
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           }.start();

       }
    }
}
